package com.wzk.canalsync.utils;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;

/**
 * @Author: WangZiKang
 * @Date: 2024/12/29 12:16
 */
@Slf4j
@Component
public class LogToFile {

    //日志打印线程池
    private static final ExecutorService threadPool = new ThreadPoolExecutor(
            1,
            1,
            0L,
            TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(10000),
            new ThreadPoolExecutor.CallerRunsPolicy()
    );

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    //把data存到名为name的log文件夹里，要传入当前类的logger
    public static boolean logToFile(String data, Logger logger, String name) {
        threadPool.submit(new Runnable() {
           @Override
           public void run() {
               try {
                   String currentDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
                   String logFileName = "logs/"+name+"/"+name+"_log_" + currentDate + ".log";
                   Path logFilePath = Paths.get(logFileName);
                   // 创建目录，如果目录不存在
                   Files.createDirectories(logFilePath.getParent());
                   // 如果文件不存在，创建新文件；如果文件已存在，以追加方式打开
                   Files.write(logFilePath, formatLogMessage(data).getBytes(), StandardOpenOption.CREATE, StandardOpenOption.APPEND);
               } catch (IOException e) {
                   log.error("日志打印失败！出现:{}",e.getMessage());
               }
           }
       });
       return true;
    }
    // 将日志数据格式化
    private static String formatLogMessage(String message) {
        return "[" + dateFormat.format(new Date()) + "] " + message + System.lineSeparator();
    }
}
